package com.learning.datastruct.collection.list;


import com.learning.datastruct.collection.MyAbstractCollection;

/**
 * @author ZLH
 */
public abstract class MyAbstractList<E> extends MyAbstractCollection<E> implements MyList<E> {
    protected static int NOTFOUND_INDEX = -1;
    protected int size = 0;

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean add(E e) {
        add(size(), e);
        return true;
    }

    @Override
    public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }

    @Override
    public boolean remove(Object o) {
        int i = indexOf(o);
        if (NOTFOUND_INDEX == i) {
            return false;
        } else {
            remove(i);
            return true;
        }
    }

    protected void rangeCheck(int index) {
        if (index >= size) {
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
        }
    }

    protected void rangeCheckForAdd(int index) {
        if (index > size || index < 0) {
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
        }
    }

    private String outOfBoundsMsg(int index) {
        return "Index: " + index + ", Size: " + size;
    }
}
